<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="类型" prop="operationType">
        <el-select v-model="queryParams.operationType" placeholder="请选择操作类型" clearable>
          <el-option
            v-for="dict in dict.type.ec_opreate_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="数量" prop="operationQuantity">
        <el-input
          v-model="queryParams.operationQuantity"
          placeholder="请输入操作数量"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单号" prop="orderNo">
        <el-input
          v-model="queryParams.orderNo"
          placeholder="请输入关联订单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="原因" prop="operationReason">
        <el-input
          v-model="queryParams.operationReason"
          placeholder="请输入操作原因"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="操作人" prop="operator">
        <el-input
          v-model="queryParams.operator"
          placeholder="请输入操作人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['fun:log:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['fun:log:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['fun:log:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['fun:log:import']"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['fun:log:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="logList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="商品" align="center" prop="productName" width="150" show-overflow-tooltip />
      <el-table-column label="创建组织" align="center" width="120">
        <template slot-scope="scope">
          <span>{{ getDeptName(scope.row.orgId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="SKU" align="center" prop="skuName" width="120" show-overflow-tooltip />
      <el-table-column label="操作类型" align="center" prop="operationType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.ec_opreate_type" :value="scope.row.operationType"/>
        </template>
      </el-table-column>
      <el-table-column label="操作数量" align="center" prop="operationQuantity" />
      <el-table-column label="操作前库存" align="center" prop="beforeStock" />
      <el-table-column label="操作后库存" align="center" prop="afterStock" />
      <el-table-column label="订单号" align="center" prop="orderNo" show-overflow-tooltip />
      <el-table-column label="操作原因" align="center" prop="operationReason" width="200" show-overflow-tooltip />
      <el-table-column label="操作人" align="center" prop="operator" width="100" show-overflow-tooltip />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['fun:log:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['fun:log:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改库存记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="SKU ID" prop="skuId">
          <el-input v-model="form.skuId" placeholder="请输入SKU ID" />
        </el-form-item>
        <el-form-item label="操作类型" prop="operationType">
          <el-select v-model="form.operationType" placeholder="请选择操作类型">
            <el-option
              v-for="dict in dict.type.ec_opreate_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="操作数量" prop="operationQuantity">
          <el-input v-model="form.operationQuantity" placeholder="请输入操作数量" />
        </el-form-item>
        <el-form-item label="操作前库存" prop="beforeStock">
          <el-input v-model="form.beforeStock" placeholder="请输入操作前库存" />
        </el-form-item>
        <el-form-item label="操作后库存" prop="afterStock">
          <el-input v-model="form.afterStock" placeholder="请输入操作后库存" />
        </el-form-item>
        <el-form-item label="关联订单号" prop="orderNo">
          <el-input v-model="form.orderNo" placeholder="请输入关联订单号" />
        </el-form-item>
        <el-form-item label="操作原因" prop="operationReason">
          <el-input v-model="form.operationReason" type="textarea" placeholder="请输入操作原因" />
        </el-form-item>
        <el-form-item label="操作人" prop="operator">
          <el-input v-model="form.operator" placeholder="请输入操作人" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 库存记录导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的库存记录数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listLog, getLog, delLog, addLog, updateLog, importLog } from "@/api/fun/log"
import { getSku } from "@/api/fun/sku"
import CacheManager from '@/utils/cacheManager'
import { getDept } from "@/api/system/dept"
export default {
  name: "Log",
  dicts: ['ec_opreate_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 库存记录表格数据
      logList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        skuId: [
          { required: true, message: "SKU ID不能为空", trigger: "blur" }
        ],
        operationType: [
          { required: true, message: "操作类型不能为空", trigger: "change" }
        ],
        operationQuantity: [
          { required: true, message: "操作数量不能为空", trigger: "blur" }
        ],
        beforeStock: [
          { required: true, message: "操作前库存不能为空", trigger: "blur" }
        ],
        afterStock: [
          { required: true, message: "操作后库存不能为空", trigger: "blur" }
        ],
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        operationType: null,
        operationQuantity: null,
        orderNo: null,
        operationReason: null,
        operator: null,
      },
      // 导入参数
      upload: {
        // 是否显示弹出层（导入）
        open: false,
        // 弹出层标题（导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的库存记录数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + this.$store.getters.token },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/fun/log/importData"
      }
    }
  },
  created() {
    this.getList()
  },
  mounted() {
    // 监听表单提交事件
    this.$eventBus.$on('refreshLogList', () => {
      this.getList()
    })
  },
  beforeDestroy() {
    // 移除事件监听器
    this.$eventBus.$off('refreshLogList')
  },
  methods: {    /** 根据部门ID获取部门名称 */
    getDeptName(deptId) {
      return CacheManager.getDeptName(deptId, getDept)
    },
    /** 查询库存记录列表 */
    getList() {
      this.loading = true
      listLog(this.queryParams).then(response => {
        this.logList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 标签页点击事件
    handleTabClick(tab) {
      if (tab.name === 'list') {
        this.showForm = false
        this.currentLogId = null
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.logId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        logId: null,
        skuId: null,
        operationType: null,
        operationQuantity: null,
        beforeStock: null,
        afterStock: null,
        orderNo: null,
        operationReason: null,
        operator: null,
        operationTime: null
      }
      this.resetForm("form")
    },
    /** 新增按钮操作 */
    handleAdd() {
      const obj = { path: "/fun/log/form", query: { pageType: "add" } };
      this.$tab.openPage("新增库存记录", obj.path, obj.query);
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const logId = row.logId || this.ids[0];
      const obj = { path: "/fun/log/form", query: { pageType: "edit", logId: logId } };
      this.$tab.openPage("修改库存记录", obj.path, obj.query);
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.logId != null) {
            updateLog(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addLog(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const logIds = row.logId || this.ids
      this.$modal.confirm('是否确认删除库存记录编号为"' + logIds + '"的数据项？').then(function() {
        return delLog(logIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('fun/log/export', {
        ...this.queryParams
      }, `log_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "库存记录导入"
      this.upload.open = true
    },
    /** 下载模板操作 */
    importTemplate() {
      const link = document.createElement('a')
      link.href = process.env.BASE_URL + 'templates/stock_log_import_template.xlsx'
      link.download = `stock_log_template_${new Date().getTime()}.xlsx`
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()

      // 显示导入结果
      if (response.code === 200) {
        this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", {
          dangerouslyUseHTMLString: true,
          callback: () => {
            this.getList() // 刷新列表
          }
        })
      } else {
        this.$modal.msgError(response.msg || "导入失败")
      }
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit()
    }
  }
}
</script>
